/* eslint-disable max-lines */
import React from 'react';
import * as api from './api';
import routes from './routes';
import * as Enum from '../Enum';
import styles from './style.css';
import PropTypes from 'prop-types';
import * as actions from './actions';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import TextInput from 'Shared/components/TextInput';
import {injectIntl, formatMessage, language} from './intl';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {getValidateStatus, approveValidate} from './validator';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import {TABLE, DATE_FORMAT, FORM_ROW_OPTIONS} from '../constants';
import {Spin, Card, Button, Table, Row, Col, Form, Radio} from 'antd';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';

class DetailPanel extends React.PureComponent {
    state = {
        isFetching: false,
        data: {},
        isValidate: false,
        activityItems: [],
        activityTarget: [],
        resultDetails: []
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        this.setState({isFetching: true});
        api.getDetail(this.props.id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        data: res.data,
                        activityItems: res.data.activityItems,
                        activityTarget: res.data.activityTarget,
                        resultDetails: res.data.resultDetails
                    });
                else
                    this.setState(({
                        isFetching: false
                    }));
            });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickAbandon = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        api.abandonData(this.props.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickSubmit = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        api.submitData(this.props.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickTakeEffect = () => {
        this.setState({loading: true});
        const data = {
            rowVersion: this.state.data.rowVersion
        };
        api.takeEffectData(this.props.id, data)
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onIsPassChange = e => {
        const value = e.target.value;
        const data = Object.assign({}, this.state.data, {
            approvedResult: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    };
    onApproveCommentChange = value => {
        const data = Object.assign({}, this.state.data, {
            approveComment: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    };
    onSubmit = () => {
        const data = this.state.data;
        const condition = {
            id: this.props.id,
            approvedResult: data.approvedResult,
            approveComment: data.approveComment,
            rowVersion: data.rowVersion
        };
        const isValid = approveValidate(condition);
        if(!isValid) {
            this.setState({
                isValidate: true
            });
            return;
        }
        this.setState({loading: true});
        actions.approveOrder(condition).then(res => {
            this.setState({loading: false});
            if(res.ok)
                this.props.successReturn();
        });
    };
    render() {
        const {data} = this.state;
        const {permissions, id} = this.props;
        const operations = [];
        if(hasPermissions(permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" href={`#${routes.update.format(id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(permissions, PERMISSION.approve) && hasPermissions(data.options, 'approve'))
            operations.push(<Button key="approve" href={`#${routes.approve.format(id)}`} size="small">{
                formatMessage({
                    id: 'detailPanel.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={id}
                placement="topLeft"
                onConfirm={this.onClickAbandon}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={id}
                placement="topLeft"
                onConfirm={this.onClickSubmit}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提报？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.submit',
                        defaultMessage: '提报'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(permissions, PERMISSION.takeEffect) && hasPermissions(data.options, PERMISSION.takeEffect))
            operations.push(<WrappedPopconfirm
                key="takeEffect"
                id={id}
                placement="topLeft"
                onConfirm={this.onClickTakeEffect}
                title={formatMessage({
                    id: 'detailPanel.validate.takeEffect',
                    defaultMessage: '是否确认生效？'
                })}>
                <Button key="takeEffect" size="small">{
                    formatMessage({
                        id: 'detailPanel.takeEffect',
                        defaultMessage: '生效'
                    })
                }</Button>
            </WrappedPopconfirm>);
        const targetcolums = [{
            title: formatMessage({
                id: 'detailPanel.column.type',
                defaultMessage: '分类'
            }),
            dataIndex: 'type',
            render: text => conventEnumValueToString(Enum.marketingActivityTargetType, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.lastDate',
                defaultMessage: '上次数据'
            }),
            dataIndex: 'lastData',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.estimateData',
                defaultMessage: '预计数据'
            }),
            dataIndex: 'estimateData',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.proportion',
                defaultMessage: '增幅比例'
            }),
            dataIndex: 'proportion',
        }];
        const colums = [{
            title: formatMessage({
                id: 'detailPanel.column.itemType',
                defaultMessage: '项目类型'
            }),
            dataIndex: 'parentMarketingActivityItemCategoryName',
            render: (text, record) => `${text}/${record.marketingActivityItemCategoryName}`
        }, {
            title: formatMessage({
                id: 'detailPanel.column.item',
                defaultMessage: '项目'
            }),
            dataIndex: 'item',
        }, {
            title: formatMessage({
                id: 'detailPanel.column.amount',
                defaultMessage: '费用'
            }),
            dataIndex: 'amount',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        const approveColums = [{
            title: formatMessage({
                id: 'detailPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approvedResult',
                defaultMessage: '审核结果'
            }),
            dataIndex: 'approvedResult',
            render: text => conventEnumValueToString(Enum.marketingActivityApprovedResult, text)
        }];
        return (
            <div>
                <Spin spinning={this.state.isFetching} className="form-standard">
                    <Card title={<Row>
                        <Col span={12}>
                            {formatMessage({
                                id: 'detailPanel.card.title',
                                defaultMessage: '活动申报信息'
                            })}
                        </Col>
                        {!this.props.type && <Col className={styles.optionBtn} span={12}>
                            {operations}
                        </Col>}
                    </Row>}>
                        <DescriptionList>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detail.operation.code',
                                defaultMessage: '编号'
                            })}>{data.code}</DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detail.operation.brandName',
                                defaultMessage: '品牌'
                            })}>{data.brandName}</DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detail.operation.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(Enum.currency, data.currency)}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.theme',
                                defaultMessage: '主题'
                            })}>{data.theme}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.background',
                                defaultMessage: '背景'
                            })}>{data.background}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detail.operation.statDate',
                                defaultMessage: '开始时间'
                            })}>{formatDateTime(data.statDate, DATE_FORMAT)}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detail.operation.endDate',
                                defaultMessage: '结算时间'
                            })}>{formatDateTime(data.endDate, DATE_FORMAT)}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.mainItem',
                                defaultMessage: '主项目'
                            })}>{data.mainItem && data.mainItem.length > 0 ? `${data.mainItem.map(item =>
                                    conventEnumValueToString(Enum.marketingStatus, item))}，` : ''}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.mainItemRemark',
                                defaultMessage: '主项目备注'
                            })}>{data.mainItemRemark}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.customerQTY',
                                defaultMessage: '目标用户量'
                            })}>{data.customerQTY}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.vehicleWarranty',
                                defaultMessage: '车辆政策'
                            })}>{data.vehicleWarranty}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.scope',
                                defaultMessage: '营销目标'
                            })}>{data.scope}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.marketingProduct',
                                defaultMessage: '营销车型'
                            })}>{data.marketingProduct && data.marketingProduct.length > 0
                                    ? data.marketingProduct.map(item =>
                                        `${item.productCategoryCode}，`) : ''}
                            </DescriptionList.Description>
                            <DescriptionList.Description term={formatMessage({
                                id: 'detailPanel.operation.content',
                                defaultMessage: '营销内容'
                            })}>{data.content}
                            </DescriptionList.Description>
                        </DescriptionList>
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPanel.table.activityTarget',
                        defaultMessage: '活动预期清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={targetcolums}
                            rowKey="id"
                            pagination={false}
                            dataSource={this.state.activityTarget}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPanel.table.activityItems',
                        defaultMessage: '活动项目清单'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={this.state.activityItems}
                            {...TABLE} />
                    </Card>
                    <Card title={formatMessage({
                        id: 'detailPanel.table.resultDetails',
                        defaultMessage: '审核记录'
                    })}>
                        <Table
                            className="white-space-nowrap"
                            columns={approveColums}
                            rowKey="id"
                            pagination={false}
                            dataSource={this.state.resultDetails}
                            {...TABLE} />
                    </Card>
                    {this.props.type && <Card title={formatMessage({
                        id: 'detailPanel.approveMessage',
                        defaultMessage: '审核信息'
                    })}>
                        <Row>
                            <Col>
                                <Form.Item
                                    style={{marginBottom: 0}}
                                    label={formatMessage({
                                        id: 'detailPanel.approvedResult',
                                        defaultMessage: '审核结果'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}
                                    validateStatus={getValidateStatus(
                                        this.state.isValidate,
                                        data.approvedResult
                                    )}
                                    required>
                                    <Radio.Group
                                        name="approvedResult"
                                        onChange={this.onIsPassChange}
                                        value={data.approvedResult}>
                                        {Enum.marketingActivityApprovedResult.toList(language).map(item =>
                                            <Radio value={item.value} key={item.value}>
                                                {formatMessage({
                                                    id: 'detailPanel.yesno',
                                                    defaultMessage: `${item.text}`
                                                })}
                                            </Radio>)}
                                    </Radio.Group>
                                </Form.Item>
                            </Col>
                            <Col>
                                <Form.Item
                                    label={formatMessage({
                                        id: 'detailPanel.approveComment',
                                        defaultMessage: '审核意见'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}
                                    validateStatus={getValidateStatus(
                                        this.state.isValidate,
                                        data.approveComment
                                    )}
                                    required>
                                    <TextInput
                                        name="approveComment"
                                        type="textarea"
                                        value={data.approveComment}
                                        onBlur={this.onApproveCommentChange} />
                                </Form.Item>
                            </Col>
                        </Row>
                    </Card>}
                    {this.props.type && <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            loading={this.state.loading}>
                            {formatMessage({
                                id: 'detailPanel.btn.submit',
                                defaultMessage: '提交'
                            })}
                        </Button>
                    </Card>}
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" onClick={this.onCancel}>{formatMessage({
                        id: 'detailPanel.operation.onCancel',
                        defaultMessage: '返回'
                    })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
    permissions: PropTypes.array
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state)
});

const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(actions.tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
